const { exec } = require('child_process')

/**
 * 根据进程名找进程PID
 */
function findPidByName() {
    var cmd = process.platform == 'win32' ? 'tasklist' : 'ps aux'
    var exec = require('child_process').exec
    var name = 'ffmpeg'
    exec(cmd, function(err, stdout, stderr) {
        if (err) {
            return console.log(err)
        }
        stdout.split('\n').filter(function(line) {
            var p = line.trim().split(/\s+/),
                pname = p[0],
                pid = p[1]
            if (pname.toLowerCase().indexOf(name) >= 0 && parseInt(pid)) {
                console.log(pname, pid)
            }
        })
    })
}

/**
 * 根据端口号关闭进程
 *  * @param {Function} fn 要执行的函数
 * @param {string} port 端口号
 */
function releasePort(fn = () => {}, port = '3667') {
    var cmd = process.platform == 'win32' ? 'netstat -ano' : 'ps aux'
    exec(cmd, function(err, stdout, stderr) {
        if (err) {
            return console.log(err)
        }
        let flag = true
        stdout.split('\n').filter(function(line) {
            var p = line.trim().split(/\s+/)
            var address = p[1]
            if (address != undefined) {
                if (address.split(':')[1] == port) {
                    exec('taskkill /F /pid ' + p[4], function(err, stdout, stderr) {
                        if (err) {
                            return console.log('释放指定端口失败！！')
                        }
                        console.log('占用指定端口的程序被成功杀掉！')
                    })
                    fn()
                    flag = false
                }
            }
        })
        if (flag) fn()
    })
}

export { findPidByName, releasePort }
